package cn.wangzg.course0501;

import androidx.annotation.LongDef;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.List;

public class MainActivity extends BaseActivity {
    // 读写权限
    private static final int REQUEST_EXTERNAL_STORAGE = 1;
    private static String[] PERMISSIONS_STORAGE = {
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE};

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //给Activity设置一个布局
        setContentView(R.layout.activity_main);

        //initView();
    }

    private void initView() {
        Button btnWrite = findViewById(R.id.button);
        btnWrite.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

            }
        });
    }

    //内部存储写文件
    public void btnFileWrite(View view) {
        String fileName = "data.txt";
        String content = "武汉加油！";
        FileOutputStream fos;
        try {
            //1.打开文件
            fos = openFileOutput(fileName, MODE_PRIVATE);
            //2.写操作
            fos.write(content.getBytes());
            //3.关闭文件
            fos.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    //内部存储读文件
    public void btnFileRead(View view) {
        String content = "";
        FileInputStream fis;
        try {
            //1.打开文件
            fis = openFileInput("data.txt");
            //2.定义数组，并读取数据
            byte[] buffer = new byte[fis.available()];
            fis.read(buffer);
            //3.将字节数组转换为字符串
            content = new String(buffer);
            //4.关闭文件
            fis.close();
            showMsg(content);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    //外部存储写文件，Android 29使用
    public void btnSdFileWriteNew(View view) {
        File SDPath = getExternalFilesDir(Environment.DIRECTORY_ALARMS);
        File file = new File(SDPath, "data.txt");
        String data = "中国加油！";
        FileOutputStream fos;
        try {
            fos = new FileOutputStream(file);
            fos.write(data.getBytes());
            fos.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //外部存储读文件，Android 29使用
    public void btnSdFileReadNew(View view) {
        File SDPath = getExternalFilesDir(Environment.DIRECTORY_ALARMS);
        File file = new File(SDPath, "data.txt");
        FileInputStream fis;
        try {
            fis = new FileInputStream(file);
            BufferedReader br = new BufferedReader(new InputStreamReader(fis));
            String data = br.readLine();
            showMsg(data);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //外部存储(SD卡)写文件
    public void btnSdFileWrite(View view) {

//        //1.检查版本是否大于M，大于M需要动态申请权限  6.0  运行时权限申请，动态
//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
//            //3.检查是否获取该权限
//            if (ContextCompat.checkSelfPermission(this, PERMISSIONS_STORAGE[1])
//                    != PackageManager.PERMISSION_GRANTED) {
//                //5.未获得权限，弹窗申请
//                ActivityCompat.requestPermissions(this,
//                        PERMISSIONS_STORAGE, REQUEST_EXTERNAL_STORAGE);
//            }else {//4.已获得权限
//                writeSdFile("data.txt","中国加油！");
//            }
//        }else {//2.否则，不需要动态申请
//            /**
//             * 6.0之前，安装App时，提示授予的权限，如果不同意，退出安装
//             * 同意，才能继续安装
//             */
//            writeSdFile("data.txt","中国加油！");
//        }

        requestRunPermisssion(PERMISSIONS_STORAGE, new PermissionListener() {
            @Override
            public void onGranted() {
                writeSdFile("data.txt", "中国加油！");
            }

            @Override
            public void onDenied(List<String> deniedPermission) {
                showMsg("未获得授权，无法完成操作！");
            }
        });
    }
//    //6.用户点击后，执行的操作
//    @Override
//    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
//                                           @NonNull int[] grantResults) {
//        if(requestCode==REQUEST_EXTERNAL_STORAGE){
//            if(grantResults[1]==PackageManager.PERMISSION_GRANTED){
//                writeSdFile("data.txt","中国加油！");
//            }
//        }else if(requestCode==2){
//            if(grantResults[0]==PackageManager.PERMISSION_GRANTED){
//                readSdFile("data.txt");
//            }
//        }
//    }

    private void writeSdFile(String name, String data) {
        //1.获得SD卡的状态：加载，未加载
        String state = Environment.getExternalStorageState();
        if (state.equals(Environment.MEDIA_MOUNTED)) {//如果加载了SD卡
            //2.获得SD卡的根目录
            File SDPath = Environment.getExternalStorageDirectory();
            File file = new File(SDPath, name);
            FileOutputStream fos;
            try {
                fos = new FileOutputStream(file);
                fos.write(data.getBytes());
                fos.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public void btnSdFileRead(View view) {
//        //检查版本是否大于M
//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
//            if (ContextCompat.checkSelfPermission(this, PERMISSIONS_STORAGE[0])
//                    != PackageManager.PERMISSION_GRANTED) {
//                ActivityCompat.requestPermissions(this,
//                        PERMISSIONS_STORAGE, 2);
//            }else {
//                readSdFile("data.txt");
//            }
//        }else{
//            readSdFile("data.txt");
//        }

        requestRunPermisssion(PERMISSIONS_STORAGE, new PermissionListener() {
            @Override
            public void onGranted() {
                readSdFile("data.txt");
            }

            @Override
            public void onDenied(List<String> deniedPermission) {
                showMsg("未获得授权，无法完成操作！");
            }
        });
    }

    private void readSdFile(String name) {
        String state = Environment.getExternalStorageState();
        if (state.equals(Environment.MEDIA_MOUNTED)) {
            File SDPath = Environment.getExternalStorageDirectory();
            File file = new File(SDPath, name);
            FileInputStream fis;
            try {
                fis = new FileInputStream(file);
                BufferedReader br = new BufferedReader(new InputStreamReader(fis));
                String data = br.readLine();
                showMsg(data);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    private void showMsg(String msg) {
        Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
    }

    public void btnXmlParse(View view) {
        //读取weather1.xml文件
        InputStream is = this.getResources().openRawResource(R.raw.weather1);
        //把每个城市的天气信息集合存到weatherInfos中
        try {
            List<WeatherInfo> weatherInfos = WeatherService.getInfosFromXML(is);
            //List<WeatherInfo> weatherInfos = WeatherService.parseXMLWithSAX(is);
            //List<WeatherInfo> weatherInfos = WeatherService.parseXMLWithDom(is);
            for (WeatherInfo info : weatherInfos) {
                Log.d("Xml:", "btnXmlParse: " +info.toString());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    public void btnJsonParse(View view) {
        //读取weather1.xml文件
        InputStream is = this.getResources().openRawResource(R.raw.weather2);
        try {
            List<WeatherInfo> infos = WeatherService.getInfosFromJson(is);
            for (WeatherInfo info : infos) {
                Log.d("Json:", "btnJsonParse: " +info.toString());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void btnLogin(View view){
        startActivity(new Intent(this,LoginActivity.class));
    }
}
